# api/app/routes.py
from flask import Blueprint, request, jsonify,Response
from flasgger import swag_from # type: ignore
from pathlib import Path
import subprocess
import logging
from .services.crawlerService import CrawlerService  # 导入封装的服务
from .services.textGenerationService import TextGenerationService  # 导入新的服务

# 初始化蓝图（必须放在文件顶部）
crawler_bp = Blueprint('crawler', __name__, url_prefix='/api/v1')
generate_bp = Blueprint('generate', __name__, url_prefix='/api/v1')

# 配置日志
logger = logging.getLogger(__name__)

@crawler_bp.route('/crawler/startCrawler', methods=['POST'])
@swag_from('docs/crawler_docs.yml')
def start_crawler():
    """
    启动爬虫任务
    """
    try:
        data = request.get_json()
        
        # 参数校验
        if not data or 'platform' not in data or 'keywords' not in data:
            logger.error("缺少必要参数")
            return jsonify({
                "status": "error",
                "message": "缺少必要参数: platform 和 keywords"
            }), 400

        # 调用封装的爬虫服务
        response = CrawlerService.start_crawler(
            platform=data['platform'],
            keywords=data['keywords'],
            login_type="cookie",
            crawl_type="search",
            save_option="json"
        )

        # 确保返回的是一个 Response 对象
        if isinstance(response, Response):
            return response
        else:
            logger.error("CrawlerService.start_crawler 返回了非 Response 对象")
            return jsonify({
                "status": "error",
                "message": "系统错误: 爬虫服务返回了非预期的响应类型"
            }), 500

    except Exception as e:
        logger.exception("爬虫启动异常")
        return jsonify({
            "status": "error",
            "message": f"系统错误: {str(e)}"
        }), 500

@crawler_bp.route('/crawler/getTotalComments', methods=['GET'])
@swag_from('docs/get_total_comments_docs.yml')
def get_total_comments():
    """
    获取已爬取的评论总数
    """
    try:
        # 获取关键词参数
        keywords = request.args.get('keywords')
        if not keywords:
            logger.error("缺少关键词参数")
            return jsonify({
                "status": "error",
                "message": "缺少关键词参数"
            }), 400

        # 调用封装的爬虫服务获取评论总数
        result = CrawlerService.get_total_comments(keywords)

        # 根据返回结果处理响应
        if result['status'] == 'success':
            return jsonify({
                "status": "success",
                "totalComments": result['totalComments']
            })
        else:
            logger.error(result['message'])
            return jsonify({
                "status": "error",
                "message": result['message']
            }), 400

    except Exception as e:
        logger.exception("获取评论总数异常")
        return jsonify({
            "status": "error",
            "message": f"系统错误: {str(e)}"
        }), 500
    
@crawler_bp.route('/crawler/getDBBase', methods=['GET'])
@swag_from('docs/get_db_base_docs.yml')
def get_db_base():
    """
    获取数据库基础信息
    """
    try:
        # 调用 crawlerService 中的 get_DB_basement 方法
        result = CrawlerService.get_DB_basement()

        # 根据返回结果处理响应
        if result['status'] == 'success':
            return jsonify({
                "status": "success",
                "dbInfo": result['dbInfo']
            })
        else:
            logger.error(result['message'])
            return jsonify({
                "status": "error",
                "message": result['message']
            }), 400

    except Exception as e:
        logger.exception("获取数据库基础信息异常")
        return jsonify({
            "status": "error",
            "message": f"系统错误: {str(e)}"
        }), 500

@generate_bp.route('/generate', methods=['POST'])
@swag_from('docs/generate_docs.yml')
def generate_text():
    """
    生成文本
    """
    try:
        data = request.get_json()
        
        # 参数校验
        if not data or 'prompt' not in data or 'number' not in data:
            logger.error("缺少必要参数")
            return jsonify({
                "status": "error",
                "message": "缺少必要参数: prompt 和 number"
            }), 400

        print("开始请求")
        # 调用文本生成服务
        result = TextGenerationService.generate_text(
            prompt=data['prompt'],
            number=data['number']
        )

        # 根据返回结果处理响应
        if result['status'] == 'success':
            return jsonify({
                "status": "success",
                "generated_texts": result['generated_texts']
            })
        else:
            logger.error(result['message'])
            return jsonify({
                "status": "error",
                "message": result['message']
            }), 400

    except Exception as e:
        logger.exception("文本生成异常")
        return jsonify({
            "status": "error",
            "message": f"系统错误: {str(e)}"
        }), 500